package com.wujian.love.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.CountDownLatch;

import cn.hutool.core.convert.Convert;
import com.alibaba.fastjson.JSON;
import com.wujian.love.contants.ClassContants;
import com.wujian.love.contants.RocketMQContants;
import com.wujian.love.domin.OrderParent;
import com.wujian.love.domin.OrderProduct;
import com.wujian.love.domin.Product;
import com.wujian.love.domin.SeckillOrder;
import com.wujian.love.dto.OrderInfoDto;
import com.wujian.love.dto.OrderProductDto;
import com.wujian.love.mapper.OrderProductMapper;
import com.wujian.love.mapper.ProductMapper;
import com.wujian.love.rocketmq.produce.SyncProducer;
import com.wujian.love.rocketmq.produce.TransactionProduce;
import com.wujian.love.utils.CodeGeneratorUtils;
import com.wujian.love.utils.MessageUtils;
import org.apache.rocketmq.client.producer.LocalTransactionState;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.client.producer.TransactionSendResult;
import org.apache.rocketmq.common.message.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.wujian.love.mapper.OrderParentMapper;
import com.wujian.love.service.IOrderParentService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 订单 服务层实现
 * 
 * @author cdw
 * @date 2020-07-06
 */
@Service
public class OrderParentServiceImpl implements IOrderParentService 
{
	@Autowired
	private OrderParentMapper orderParentMapper;

	@Autowired
	private ProductMapper productMapper;

	@Autowired
	private OrderProductMapper orderProductMapper;

	@Autowired
	private TransactionProduce transactionProduce;

	@Autowired
	private SyncProducer syncProducer;




	/**
     * 查询订单信息
     * 
     * @param id 订单ID
     * @return 订单信息
     */
    @Override
	public OrderParent selectOrderParentById(Integer id)
	{
	    return orderParentMapper.selectOrderParentById(id);
	}
	
	/**
     * 查询订单列表
     * 
     * @param orderParent 订单信息
     * @return 订单集合
     */
	@Override
	public List<OrderParent> selectOrderParentList(OrderParent orderParent)
	{
	    return orderParentMapper.selectOrderParentList(orderParent);
	}
	
    /**
     * 新增订单
     * 
     * @param orderParent 订单信息
     * @return 结果
     */
	@Override
	public int insertOrderParent(OrderParent orderParent)
	{
	    return orderParentMapper.insertOrderParent(orderParent);
	}
	
	/**
     * 修改订单
     * 
     * @param orderParent 订单信息
     * @return 结果
     */
	@Override
	public int updateOrderParent(OrderParent orderParent)
	{
	    return orderParentMapper.updateOrderParent(orderParent);
	}

	/**
     * 删除订单对象
     * 
     * @param ids 需要删除的数据ID
     * @return 结果
     */
	@Override
	public int deleteOrderParentByIds(String ids)
	{
		return orderParentMapper.deleteOrderParentByIds(Convert.toStrArray(ids));
	}


	/**
	 * @Author WuJian
	 * @Description //创建订单
	 * @Date 9:27 2020/6/17
	 * @Param [dto]
	 * @return java.util.Map<java.lang.String,java.lang.Object>
	 **/
	@Override
	@Transactional(rollbackFor = Exception.class)
	public Map<String, Object> createOrderParent(OrderInfoDto dto) throws Exception{
		Map<String,Object> resultMap = new HashMap<>();
		//下单
		//查询到商品库存的版本号
		List<OrderProductDto> productList = dto.getList();
		//校验当前商品是否存在并且判断库存数是否足够
		boolean flag = checkProductNum(productList);
		if(flag){
			//库存足够,生成订单
			OrderParent orderParent = new OrderParent();
			orderParent.setOrderNo(CodeGeneratorUtils.nextId());
			//订单状态(待支付)
			orderParent.setOrderStatus(OrderParent.WAIT_ORDER_PAY);
			orderParent.setDelFlag(ClassContants.NOT_DEL_FLAG);
			//订单金额(购买金额)
			orderParent.setOrderAmount(dto.getBuyMoney());
			//保存订单
			int rowOrderParent = orderParentMapper.insertOrderParent(orderParent);
			if(rowOrderParent > 0){
				//获取到订单Id
				Integer orderParentId = orderParent.getId();
				//创建订单商品表
				for (OrderProductDto OrderParentProductDto : productList) {
					OrderProduct orderProduct = new OrderProduct();
					orderProduct.setOrderId(orderParentId);
					//查询到当前的商品
					Product product = productMapper.selectProductById(OrderParentProductDto.getProductId());
					orderProduct.setProductId(OrderParentProductDto.getProductId());
					orderProduct.setProductNum(OrderParentProductDto.getNumber());
					//计算商品当前商品的总价(数量*价格)
					Long productAmount = OrderParentProductDto.getNumber() * product.getProductMoney();
					orderProduct.setProductPrice(productAmount);
					orderProductMapper.insertOrderProduct(orderProduct);
				}
				//订单创建完成,需要发送延迟消息.超过多长时间没有支付会自动取消订单

				Map<String, Object> params = new HashMap<>();
				params.put("orderParentId", orderParentId);
				params.put("MSG_TYPE", orderParentId);


                //	同步阻塞
                //CountDownLatch countDownLatch = new CountDownLatch(1);
                //params.put("currentCountDown", countDownLatch);
				//创建延时消息
				Message cancelMessage = MessageUtils.createCancelOrderMessage(params);
				//创建订单扣减消息
				Message stockMessage = MessageUtils.createStockOrderMessage(params);
				//发送扣减库存消息
				TransactionSendResult stockResult = transactionProduce.sendMessage(stockMessage, RocketMQContants.STOCK_ORDER_MSG_TYPE);

				//发送延时未支付取消订单消息
				SendResult cancelResult = syncProducer.sendMessage(cancelMessage);
               	// countDownLatch.await();
                // 当消息发送成功，本地事务也执行成功时
				if(stockResult.getSendStatus() == SendStatus.SEND_OK
						&& stockResult.getLocalTransactionState() == LocalTransactionState.COMMIT_MESSAGE) {
					//	回调OrderParent通知支付成功消息

				} else {




				}



			}



		}else{
			resultMap.put("flag",false);
			resultMap.put("value","当前商品库存不足,请重新下单");
			return resultMap;
		}




		return null;
	}

	@Override
	public SeckillOrder getOrderByUserIdGoodsId(Long id, long goodsId) {
		return null;
	}


	private  boolean checkProductNum(List<OrderProductDto> productList){
		for (OrderProductDto OrderProductDto : productList) {

		}

		return true;

	}
}
